#!/usr/bin/Rscript
# setwd("/home/zhang/BMK/test/cuffdiff")
setwd("F:/cuffdiff/")

# 生成文件列表
y <- list.files(pattern = "david.xlsx")

read.kegg <- function(input){
  if(!require(openxlsx)){
    install.aocakges("openxlsx")
    if(!require(openxlsx)){
      stop("openxlsx install failed")
    }
  }
  input <- read.xlsx(as.character(input), sheet = 1)
  
  # 用来计算RichFactor，用的是其中的BgRatio
  caculate.richfactor <- function(input){
    value <- unlist(strsplit(input[4], "/"))
    return(as.numeric(as.character(value[1]))/as.numeric(as.character(value[2])))
  }
  
  input$RichFactor <- apply(input, 1, caculate.richfactor)

  return(input)
}

# 根据clusterProfile包的结果，画kegg的图
draw.clusterprofile <- function(input)
{
  if(!require(ggplot2)){
    install.packages("ggplot2")
    if(!require(ggplot2)){
      stop("ggplot2 install failed")
    }
  }
  
  # window specific
  # 改变字体为Times New Roman
  windowsFonts(NRM = windowsFont("Times New Roman"))
  old_theme <- theme_update(axis.text = element_text(family = "NRM", size = 18, color = "black"),
                            legend.key.size = unit(1.2, "cm"),
                            axis.title = element_text(family = "NRM", size = 18),
                            legend.text = element_text(family = "NRM", size = 18))
  
  p <- ggplot(input,
              aes(x = RichFactor,
                  y = reorder(Description, qvalue, sort),
                  colour = qvalue,
                  size = Count)
  ) + geom_point() + scale_colour_gradientn(colours=rainbow(4)) + ylab("Description")
  return(p)
}

tem <- read.kegg(y[1])
name <- gsub("xlsx", "tiff", y[1])
tiff(name, units = "in", width = 12, height = 10, compression = "lzw", res = 600)
draw.clusterprofile(tem) + theme(text = element_text(size=20))
dev.off()

tem <- read.kegg(y[2])
name <- gsub("xlsx", "tiff", y[2])
tiff(name, units = "in", width = 12, height = 10, compression = "lzw", res = 600)
draw.clusterprofile(tem) + theme(text = element_text(size=20))
dev.off()

tem <- read.kegg(y[3])
name <- gsub("xlsx", "tiff", y[3])
tiff(name, units = "in", width = 12, height = 10, compression = "lzw", res = 600)
draw.clusterprofile(tem) + theme(text = element_text(size=20))
dev.off()

tem <- read.kegg(y[4])
name <- gsub("xlsx", "tiff", y[4])
tiff(name, units = "in", width = 12, height = 10, compression = "lzw", res = 600)
draw.clusterprofile(tem) + theme(text = element_text(size=20))
dev.off()

tem <- read.kegg(y[5])
name <- gsub("xlsx", "tiff", y[5])
tiff(name, units = "in", width = 12, height = 10, compression = "lzw", res = 600)
draw.clusterprofile(tem) + theme(text = element_text(size=20))
dev.off()

tem <- read.kegg(y[6])
name <- gsub("xlsx", "tiff", y[6])
tiff(name, units = "in", width = 12, height = 10, compression = "lzw", res = 600)
draw.clusterprofile(tem) + theme(text = element_text(size=20))
dev.off()



